﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using mshtml;
using System.Web;
using HtmlAgilityPack;
using log4net;
using log4net.Config;

namespace CapchaUserControl
{
    public partial class Form1 : Form,ISending
    {
        ILog log = LogManager.GetLogger(typeof(Form1));
        public static string keyWord = "FAP Captcha 123456789";
        public static string keyWord_xpath = "%";
        public static string keyWord_return = "%";
        private List<CapchaUserControl> lCaptcha;
        Point p;

        public Form1()
        {
            log4net.Config.BasicConfigurator.Configure();
            InitializeComponent();
            //kết nối server
            log.Info("NHUT - Da khoi tao log4net");
            FAP.CaptchaCenter.CaptchaClient.OnReceiveClientCaptcha += CaptchaClient_OnReceiveClientCaptcha;
            try
            {
                FAP.CaptchaCenter.CaptchaClient.SendCaptcha("hello");//chuỗi thiết lập kết nối
            }
            catch (NullReferenceException ex)
            {
                log.Error("NHUT - Client khong ket noi duoc voi socket server. \r\nChi tiet loi: " + ex.ToString());
            }

        }

        /// <summary>
        /// Hàm nhận thông tin captcha từ server
        /// </summary>
        /// <param name="_strCaptcha">Doan thong tin chua captcha co cau truc theo quy dinh, gom co id xpath va htmlstring</param>
        void CaptchaClient_OnReceiveClientCaptcha(string _strCaptcha)
        {

            log.Info("NHUT - Client da nhan duoc thong tin tu server");

            string[] tokens = _strCaptcha.Split(new string[] { keyWord }, StringSplitOptions.None);

            if (tokens.Length != 4)
            {
                log.Warn("NHUT - Du lieu gui xuong client khong du tham so {id-xpath-htmlString-humanverify}");
                return;
            }

            //goi su kien tạo usercontrol nhập captcha
            try
            {
                this.Invoke((MethodInvoker)delegate
                {
                    this.AddCaptchaControl(tokens);
                });
            }
            catch (Exception ex)
            {
                log.Error("NHUT - Loi khi invoke ham AddCaptchaControl.\r\nChi tiet loi: " + ex.ToString());
            }
           

        }

        private void AddCaptchaControl(string[] tokens)
        {
            CapchaUserControl captcha = new CapchaUserControl(tokens[0], this);// loi ngay ham nay, pahi thuc hien tren main thread moi dc
            captcha.LoadCapcha(tokens[2], tokens[1], tokens[3]);//htmlString, Xpath, HumanVerify name

            captcha.getTextBox().KeyDown += textbox_KeyDown;
            captcha.getWebBrowser().DocumentCompleted += WebBrowser_DocumentCompleted;
            
            lCaptcha.Add(captcha);
            if (lCaptcha.Count == 1)
            {
                refreshUI();
            }
            
        }

        void textbox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextBox t = (TextBox)sender;
                CapchaUserControl c = (CapchaUserControl)t.Parent;
                c.keyEnter();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lCaptcha = new List<CapchaUserControl>();
            p = panelUC.Location;

            ////code tam
            //string url = "http://phimtv.net/member/register";
            //HtmlWeb web = new HtmlWeb();
            //HtmlAgilityPack.HtmlDocument doc = web.Load(url);

            ////remove tag META va tag SCRIPT
            //foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//*"))
            //{
            //    if (node.Name.ToLower().Equals("meta") || node.Name.ToLower().Equals("script") || node.Name.ToLower().Equals("style"))
            //    {
            //        node.Remove();
            //    }
            //}

            //CapchaUserControl captcha = new CapchaUserControl("1", this);// loi ngay ham nay, pahi thuc hien tren main thread moi dc
            //captcha.LoadCapcha(doc.DocumentNode.InnerHtml, "", "");

            //captcha.getTextBox().KeyDown += textbox_KeyDown;
            //captcha.getWebBrowser().DocumentCompleted += WebBrowser_DocumentCompleted;

            //lCaptcha.Add(captcha);

            //if (lCaptcha.Count == 1)
            //{
            //    refreshUI();
            //}
            ////end code tam
            

        }

        void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            CapchaUserControl captcha = lCaptcha[0];
            captcha.getWebBrowser().Document.Body.Click += webbrowser_Click;    
        }

        void webbrowser_Click(object sender, HtmlElementEventArgs e)
        {
            lCaptcha[0].setTextBoxFocus();
        }

        // goi thuc hien khi co hanh dong add hay remove i item trong list
        private void refreshUI()
        {
            panelUC.Controls.Clear();
            if (lCaptcha.Count != 0)
            {
                lCaptcha[0].Location = p;
                lCaptcha[0].getTextBox().Focus();

                panelUC.Controls.Add(lCaptcha[0]);
                panelUC.Controls[0].Dock = DockStyle.Fill;
            }
            
        }

        public void onSending(string _webId, string _captcha, string _human)
        {
            //format gui len server cach nhau bang dau % : id%ccaptcha%human
            //string value = _webId + keyWord_return + _captcha + keyWord_return + _human;
            //CaptchaClient.SendCaptcha(value);
            log.Info("NHUT - Da gui du lieu tra ve cho server");

            //remove user control
            for (int i = 0; i < lCaptcha.Count; i++)
            {
                if (lCaptcha[i].WebId == _webId)
                {
                    lCaptcha.RemoveAt(i);
                }
            }
            refreshUI();
        }
    }
}
